package com.yanqu.road.server.gameplayer.module.activity.tradewar;

import com.yanqu.road.entity.activity.*;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.logic.bussiness.player.UserActivityBussiness;
import com.yanqu.road.logic.bussiness.player.UserTradeWarActivityBussiness;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.pb.commonactivity.CommonActivityProto;
import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.pb.rank.YRankProto;
import com.yanqu.road.pb.tradewaractivity.TradeWarActivityProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityModule;
import com.yanqu.road.server.gameplayer.module.banquet.BanquetModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.DecorationModule;
import com.yanqu.road.server.logic.activity.condition.BaseActivityCondition;
import com.yanqu.road.server.logic.activity.tradewar.TradeWarActivityData;
import com.yanqu.road.server.logic.activity.tradewar.condition.BaseTradeWarActivityCondition;
import com.yanqu.road.server.manger.activity.*;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.manger.union.UnionActivityMgr;
import com.yanqu.road.server.pb.TradeWarActivityPb;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TradeWarActivityModule extends GeneralModule {

    private Map<Integer, Map<Integer, TradeWarActivityData>> activityDataMap;

    public TradeWarActivityModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        for(Map<Integer, TradeWarActivityData> dataMap : activityDataMap.values()) {
            for (TradeWarActivityData activityData : dataMap.values()) {
                for (UserActivityConditionData conditionData : activityData.getUserActivityConditionDataList()) {
                    if (conditionData.isInsertOption()) {
                        UserTradeWarActivityBussiness.addUserActivityConditionData(conditionData);
                    } else if (conditionData.isUpdateOption()) {
                        UserTradeWarActivityBussiness.updateUserActivityConditionData(conditionData);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean loadData() {
        activityDataMap = new ConcurrentHashMap<>();
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo();
        if(null != activityInfo) {
            Map<Integer, List<UserActivityConditionData>> userActivityConditionDataMap = UserTradeWarActivityBussiness.getUserActivityConditionDataMap(player.getUserId(),
                    activityInfo.getActivityId());
            if (null != userActivityConditionDataMap) {
                for (Map.Entry<Integer, List<UserActivityConditionData>> dataEntry : userActivityConditionDataMap.entrySet()) {
                    addActivity(activityInfo, dataEntry.getValue(), dataEntry.getKey(), false);
                }
            }
            addNewActivity();
        }
        return true;
    }

    @Override
    public void loginSendMsg() {
        addNewActivity();
        syncActivity();
    }

    public void syncActivity(){
        Map<Integer, TradeWarActivityData> dataMap = new ConcurrentHashMap<>();
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo();
        if(null != activityInfo){
            dataMap = activityDataMap.get(activityInfo.getActivityId());
        }
        TradeWarActivityProto.TradeWarActivityDetailMsg.Builder detailMsg = TradeWarActivityMgr.getTradeWarActivityDetailMsg(dataMap, player.getLanguage());
        if(null != detailMsg) {
            player.sendPacket(Protocol.U_TRADE_WAR_ACTIVITY_DETAIL, detailMsg);
        }
    }

    public void addNewActivity() {
        synchronized (this) {
            ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo();
            if (null != activityInfo) {
                Map<Integer, List<ActivityConditionInfo>> dataMap = TradeWarActivityMgr.getActivityConditionInfoMap(activityInfo.getActivityId());
                if (null != dataMap) {
                    for (int type : dataMap.keySet()) {
                        addActivity(activityInfo, new ArrayList<>(), type, true);
                    }
                }
                Map<Integer, TradeWarActivityData> tempActivityDataMap = getActivityDataMap(activityInfo.getActivityId());
                if (null != tempActivityDataMap) {
                    for (TradeWarActivityData activityData : tempActivityDataMap.values()) {
                        for (BaseTradeWarActivityCondition baseActivityCondition : activityData.getBaseActivityConditionList()) {
                            if (null != baseActivityCondition) {
                                baseActivityCondition.initValue();
                            }
                        }
                    }
                }
            }
        }
    }

    private Map<Integer, TradeWarActivityData> getActivityDataMap(int activityId){
        return activityDataMap.get(activityId);
    }

    private void addActivity(ActivityInfo activityInfo, List<UserActivityConditionData> conditionDataList, int type, boolean isNew) {
        synchronized (this) {
            if (null != activityInfo) {
                if (!activityDataMap.containsKey(activityInfo.getActivityId())) {
                    activityDataMap.put(activityInfo.getActivityId(), new ConcurrentHashMap<>());
                }

                Map<Integer, TradeWarActivityData> dataMap = activityDataMap.get(activityInfo.getActivityId());
                if (dataMap.containsKey(type)) {
                    return;
                }
                List<ActivityConditionInfo> conditionInfoList = TradeWarActivityMgr.getActivityConditionInfoList(activityInfo.getActivityId(), type);
                if (null == conditionInfoList) {
                    return;
                }

                TradeWarActivityData activityData = new TradeWarActivityData(player, activityInfo, conditionDataList);
                for (ActivityConditionInfo conditionInfo : conditionInfoList) {
                    if (activityData.continueAdd(conditionInfo.getType())) {
                        BaseTradeWarActivityCondition baseActivityCondition = BaseTradeWarActivityCondition.createActivityCondition(player, activityData, conditionInfo);
                        if (null != baseActivityCondition) {
                            activityData.addCondition(baseActivityCondition);
                            if (isNew) {
                                UserActivityConditionData userConditionData = ActivityMgr.initUserActivityConditionData(player, conditionInfo);
                                activityData.addUserActivityConditionData(userConditionData);
                            }
                        }
                    }
                }
                dataMap.put(type, activityData);
                activityData.addToPlayer();
            }
        }
    }

    /**
     * 领取跨服冲榜活动奖励
     */
    public ActivityRewardResult getRankReward(int activityId, int conditionId, boolean isCrossNotify, int myRank, int position) {
        ActivityRewardResult result = new ActivityRewardResult();
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo(activityId);
        if(null == activityInfo){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        Map<Integer, TradeWarActivityData> dataMap = activityDataMap.get(activityId);
        if(null == dataMap){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        ActivityConditionInfo activityConditionInfo = TradeWarActivityMgr.getActivityConditionInfo(activityId, conditionId);
        if(null == activityConditionInfo){
            result.setRet(GameErrorCode.E_ACTIVITY_GET_REWARD_CONDITION_ERROR);
            return result;
        }
        TradeWarActivityData activityData = dataMap.get(activityConditionInfo.getType());
        if (null == activityData) {
            result.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
            return result;
        }
        if (!ActivityMgr.activityInRewardPeriod(activityInfo)) {//不在领奖期
            result.setRet(GameErrorCode.E_ACTIVITY_NO_IN_GET_REWARD_TIME);
            return result;
        }
        if (!ActivityMgr.activityInCanRewardPeriod(activityInfo)) {
            result.setRet(GameErrorCode.E_ACTIVITY_IN_REWARD_SETTLEMENT_TIME);
            return result;
        }
        UserActivityConditionData conditionData = activityData.getFirstConditionData();
        if(null == conditionData){
            result.setRet(GameErrorCode.E_ACTIVITY_NO_JOIN);
            return result;
        }
        if (conditionData.isGetReward()) {
            result.setRet(GameErrorCode.E_ACTIVITY_REWARD_IS_GET);
            return result;
        }
        String unionUid = "";
       /* if(activityConditionInfo.getType() == eGamePlayerEventType.CrossTradeWarUnionScoreRiseRank.getValue()) {
            UnionActivityConditionData unionActivityConditionData = TradeWarActivityRankMgr.getUnionActivityConditionData(activityId, player.getUserId());
            if (null == unionActivityConditionData) {
                result.setRet(GameErrorCode.E_ACTIVITY_NO_JOIN);
                return result;
            }
            unionUid = unionActivityConditionData.getUnionUid();
        }*/
        if (!isCrossNotify) {
            // 商会分组活动走这边
            if (UnionActivityGroupHelper.isGroupActivityType(activityInfo.getType())) {
                if (activityConditionInfo.getType() == eGamePlayerEventType.CrossTradeWarScoreRiseRank.getValue()) {
                    YRankProto.YRankReqMsg.Builder builder = YRankProto.YRankReqMsg.newBuilder();
                    builder.setActivityId(activityId);
                    builder.setGroupId(GameUnionActivityGroupMgr.getGroupId(activityId, player.getUserId()));
                    builder.setIdKey(String.valueOf(activityConditionInfo.getType()));
                    builder.setRewardConditionId(conditionId);
                    player.sendUnionActivityGroupPacket(CrossProtocol.C2_CROSS_YRANK_GET_USER_RANK_TO_REWARD, builder, activityId);
                    return result;
                } else if (activityConditionInfo.getType() == eGamePlayerEventType.CrossTradeWarUnionScoreRiseRank.getValue()) {
                    YRankProto.YRankReqMsg.Builder builder = YRankProto.YRankReqMsg.newBuilder();
                    builder.setActivityId(activityId);
                    builder.setGroupId(GameUnionActivityGroupMgr.getGroupId(activityId, player.getUserId()));
                    builder.setIdKey(String.valueOf(activityConditionInfo.getType()));
                    builder.setRewardConditionId(conditionId);
                    player.sendUnionActivityGroupPacket(CrossProtocol.C2_CROSS_YRANK_GET_UNION_RANK_TO_REWARD, builder, activityId);
                    return result;
                }
            }
            //发送请求到跨服获取排名
            CrossActivityProto.CrossActivityGetRewardReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityGetRewardReqMsg.newBuilder();
            reqMsg.setActivityId(activityId);
            reqMsg.setConditionId(conditionData.getConditionId());
            reqMsg.setUnionUid(unionUid);
            player.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_TRADE_WAR_GET_REWARD, reqMsg, activityId);
            return result;
        } else {
            ActivityConditionInfo conditionInfo = TradeWarActivityMgr.getActivityConditionInfoByRank(activityId, activityConditionInfo.getType(), myRank);
            if(null == conditionInfo) {
                result.setRet(GameErrorCode.E_ACTIVITY_CONDITION_NO_COMPLETE);
                return result;
            }
            if(TradeWarActivityMgr.CONDITION_TYPE_UNION == conditionInfo.getType()) {
                    //根据职位获取奖励
                    result.setReward(UnionActivityMgr.getUnionMemberPositionDataReward(position,conditionInfo,player.getUserId()));
                    player.getModule(CurrencyModule.class).addCurrency(result.getReward(), eLogMoneyType.Activity, eLogMoneyType.CrossTradeWarActivityUnionRankReward);
            }else {
                player.getModule(CurrencyModule.class).addCurrency(conditionInfo.getReward(), eLogMoneyType.Activity, eLogMoneyType.CrossTradeWarActivityRankReward);
                result.setReward(conditionInfo.getRewardStr());
            }
            conditionData.setGetReward(true);
            onActivityDataChange(activityData);
            activityData.finish(conditionData.getConditionId());

            String rewardStr = result.getReward();
            if (rewardStr != null) {
                Property property = PropertyHelper.parseStringToProperty(rewardStr);
                if (property != null) {
                    //记录跨服称号包含的区服id
                    property.getGoods().forEach((k,v)->{
                        if (GoodsMgr.isDecorationGoods(k)) {
                            player.getModule(DecorationModule.class).setServerIds(k, activityInfo.getActivityId(), activityInfo.getServerListStr());
                        }
                    });
                    player.getModule(BanquetModule.class).getCrossBanquetInvitationReward(rewardStr,activityInfo.getServerListStr());
                }
            }

            LogMgr.addLogActivityReward(player.getUserId(), activityId, activityInfo.getType(), activityInfo.getChildType(),
                    activityConditionInfo.getConditionId(), myRank, false, result.getReward());
            return result;
        }
    }

    public void nickNameChange(){
        ActivityInfo activityInfo = TradeWarActivityMgr.getOpenActivityInfo();
        if(null != activityInfo) {
            Map<Integer, TradeWarActivityData> dataMap = activityDataMap.get(activityInfo.getActivityId());
            if(null != dataMap) {
                TradeWarActivityData activityData = dataMap.get(TradeWarActivityMgr.CONDITION_TYPE_UNION);
                if(null != activityData){
                    List<UserActivityConditionData> dataList = activityData.getUserActivityConditionDataList();

                }
            }
        }
    }

    public void onActivityDataChange(TradeWarActivityData activityData){
        CommonActivityProto.CommonActivityDataMsg.Builder dataMsg = TradeWarActivityPb.parseCommonActivityDataMsg(activityData);
        if(null != dataMsg) {
            player.sendPacket(Protocol.U_TRADE_WAR_ACTIVITY_DATA_SYNC, dataMsg);
        }
    }

    public UserActivityConditionData getUserActivityConditionData(int activityId){
        Map<Integer, TradeWarActivityData> dataMap = activityDataMap.get(activityId);
        if(null != dataMap){
            TradeWarActivityData activityData = dataMap.get(TradeWarActivityMgr.CONDITION_TYPE_UNION);
            if(null != activityData){
                return activityData.getFirstConditionData();
            }
        }
        return null;
    }
}
